import java.util.Arrays;

public class PriorityQueue_Work {
    public int[] elem;
    public int usedSize;

    public PriorityQueue_Work() {
        elem=new int[10];
    }

    /**
     * 建堆的时间复杂度：
     *
     * @param array
     */
    public void createHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            if (isFull()) elem= Arrays.copyOf(elem,2*elem.length);
            elem[i]=array[i];
            usedSize++;
        }
        for (int i = (usedSize-1-1)/2; i >=0; i--) {
            shiftDown(i,usedSize);
        }
    }

    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int root,int len) {
        int child =  2*root+1;
        while(child<len){
            if(child+1<len&&elem[child]<elem[child+1]){
                child+=1;
            }
            if(elem[child]>elem[root]){
                int tmp = elem[child];
                elem[child] = elem[root];
                elem[root]=tmp;

                root=child;
                child=2*root+1;
            }else return ;
        }
    }


    /**
     * 入队：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if(isFull()){
            elem=Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize]=val;
        shiftUp(usedSize);
        usedSize++;
    }

    private void shiftUp(int child) {
        int root = (child-1)/2;
        while(child>0){
            if (elem[root]<elem[child]){
                int tmp = elem[child];
                elem[child]=elem[root];
                elem[root]=tmp;

                child=root;
                root=(child-1)/2;
            }else return ;
        }
    }

    public boolean isFull() {
        return usedSize==elem.length;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public void pollHeap() {
        int tmp=elem[0];
        elem[0]=elem[usedSize-1];
        elem[usedSize-1]=tmp;
        usedSize--;
        shiftDown(0,usedSize);
    }

    public boolean isEmpty() {
        return usedSize==0;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() {
        return elem[0];
    }
}